package com.ayz.gateway.core.core.handlers;

import cn.hutool.log.Log;

import com.ayz.gateway.common.result.GatewayResult;
import com.ayz.gateway.common.result.ResponseCode;
import com.ayz.gateway.core.context.config.Configuration;
import com.ayz.gateway.core.core.BaseHandler;
import com.ayz.gateway.core.core.HttpResponseParser;
import com.ayz.gateway.core.core.common.AgreementConstants;
import com.ayz.gateway.core.session.GatewaySessionFactory;
import com.ayz.gateway.core.session.defaults.DefaultGatewaySession;
import com.ayz.gateway.core.session.http.HttpStatement;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @ClassName SessionServerHandler
 * @Description TODO: 网关网络通信处理器 只处理网络通信然后开启会话
 * @Author 快乐的星球
 * @Date 2023/5/5 17:35
 * @Version 1.0
 **/
@EqualsAndHashCode(callSuper = true)
@Data
public class GatewayServerHandler extends BaseHandler<FullHttpRequest> {

    private final Log log = Log.get(GatewayServerHandler.class);
    /**
     * 网关生命周期的配置项
     */
    private Configuration configuration;
    /**
     * 网关上下文单例的 会话工厂
     */
    private GatewaySessionFactory gatewaySessionFactory;

    public GatewayServerHandler(Configuration configuration, GatewaySessionFactory gatewaySessionFactory){
        this.configuration=configuration;
        this.gatewaySessionFactory=gatewaySessionFactory;
    }
    @Override
    public void openSession(ChannelHandlerContext channelHandlerContext, Channel channel, FullHttpRequest request) {
        log.info("消息处理模块处理请求;uri:{},method:{}",request.uri(),request.method());
        HttpStatement httpStatement = channel.attr(AgreementConstants.HTTP_STATEMENT).get();
        //开启会话
        DefaultGatewaySession gatewaySession = (DefaultGatewaySession) this.gatewaySessionFactory.openSession();
        gatewaySession.setConfiguration(configuration);
        gatewaySession.setHttpStatement(httpStatement);
        gatewaySession.setResponseCallback((result)->{
            //TODO: 处理响应
            GatewayResult gatewayResult=(GatewayResult) result;
            //封装GatewayResult为Http响应返回给客户端
            FullHttpResponse response = HttpResponseParser.parse(gatewayResult);
            channel.writeAndFlush(response);
        });
        //启动会话完成调用
        try {
            gatewaySession.open();
        } catch (Exception e) {
            log.warn("网关消息处理模块,开启会话出错!");
            DefaultFullHttpResponse response=(DefaultFullHttpResponse) HttpResponseParser
                    .parse(GatewayResult.error(ResponseCode.SERVER_HANDLE_FAILED,"网关消息处理模块,开启会话出错!"));
            channel.writeAndFlush(response);
        }
    }

}
